package com.example.elm.Account

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.appcompat.app.AppCompatActivity
import com.example.elm.databinding.LoginBinding
import com.example.elm.Public.AccountInfo
import com.example.elm.Public.MyApplication
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.StringReader
import kotlin.concurrent.thread

class LoginActivity : ComponentActivity() {
    private lateinit var binding: LoginBinding
    private val server_ip = MyApplication.serverIp
    private val accountList = ArrayList<AccountInfo>()
    private var dbHelper = AccountDatabase(this, "Account.db", 1)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = LoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        GetAllAccount()

        binding.back.setOnClickListener {
            val intent = Intent()
            intent.putExtra("info",AccountInfo("", "", "", "", "", ""))
            setResult(RESULT_OK, intent)
            finish()
        }

        binding.loginButton.setOnClickListener {
            val phone = binding.username.text.toString()
            val password = binding.password.text.toString()
            Log.d("username", "${phone}")
            Log.d("password", "${password}")
            if (phone.isEmpty())
                Toast.makeText(this, "账号不可为空",Toast.LENGTH_SHORT).show()
            else if (password.isEmpty())
                Toast.makeText(this, "密码不可为空",Toast.LENGTH_SHORT).show()
            else{
                var accountExists = false
                var new = AccountInfo("","","","","","")
                for (accounts in accountList) {
                    if (accounts.account == phone) {
                        accountExists = true
                        new = accounts
                        break
                    }
                }
                if (accountExists == false){
                    Toast.makeText(this, "未找到该账号", Toast.LENGTH_SHORT).show()
                    binding.username.text.clear()
                }
                else if(new.password != password){
                    Log.d("new.password", "${new.password}")
                    Toast.makeText(this, "密码不正确", Toast.LENGTH_SHORT).show()
                    binding.password.text.clear()
                }
                else{
                    Toast.makeText(this, "登录成功",Toast.LENGTH_SHORT).show()
                    MyApplication.login = true //登录成功的标志
                    val intent = Intent()
                    intent.putExtra("info", new)
                    setResult(RESULT_OK, intent)
                    finish()
                }
            }
        }

        binding.registerRedirect.setOnClickListener{
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }
    }

    fun GetAllAccount(){
        val Account_all = "http://$server_ip:8080/Account/get_all_Account.jsp"
        thread {
            try{
                val client = OkHttpClient()
                val request: Request = Request.Builder()
                    .url(Account_all)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (!responseData.isNullOrEmpty()) {
                    parseXml(responseData.toString().trim())
                    Log.d("GetAllAccount()", "有数据")
                } else {
                    Toast.makeText(this, "没有数据", Toast.LENGTH_LONG).show()
                    Log.d("GetAllAccount()", "没有数据")
                }
            }
            catch (e: Exception){
                e.printStackTrace()
                Log.d("GetAllAccount()", "网络错误")
            }
        }
    }

    fun parseXml(xmlStr: String): String{
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullPaser = factory.newPullParser()
            // 设置xml解析器的输入
            xmlPullPaser.setInput(StringReader(xmlStr))
            accountList.clear()
            var eventType = xmlPullPaser.eventType//  事件类型
            var phone = ""
            var password = ""
            var name = ""
            var people_name = ""
            var head_image = ""
            var introduction = ""
            while(eventType != XmlPullParser.END_DOCUMENT){
                val nodeName = xmlPullPaser.name
                // builder.append("${nodeName}--")
                when(eventType) {
                    // 标签开始
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "phone" -> phone = xmlPullPaser.nextText()
                            "password" -> password = xmlPullPaser.nextText()
                            "name" -> name = xmlPullPaser.nextText()
                            "people_name" -> people_name = xmlPullPaser.nextText()
                            "head_image" -> head_image  = xmlPullPaser.nextText()
                            "introduction" -> introduction = xmlPullPaser.nextText()
                        }
                    }
                    // 标签结束
                    XmlPullParser.END_TAG -> {
                        if ("Account" == nodeName) {
                            accountList.add(AccountInfo(phone, password, name, people_name, head_image, introduction))
                            Log.d("GetAllAccount()", "成功加入数据")
                        }
                    }
                }
                eventType = xmlPullPaser.next() //  读取下一个，进行遍历
            }
        }
        catch (e: Exception){
            e.printStackTrace()
        }
        return ""
    }

}